import { tokenuserinfo } from "@/api/vadmin/login";
import {
  getToken,
  removeToken,
  setToken,
  setUserInfo,
  getUserInfo,
  getroleUserColumns
} from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: getUserInfo() ? getUserInfo().info.user_name : "",
    avatar: getUserInfo() ? getUserInfo().avatar : "",
    roles: [],
    permissions: getUserInfo() ? getUserInfo().permissions : [],
    userInfo: getUserInfo(),
    roleUserColumns: getroleUserColumns()
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_UNREAD_MSG_COUNT: (state, unread_msg_count) => {
      state.unread_msg_count = unread_msg_count;
    },
    SET_USERINFO: (state, data) => {
      state.userInfo = data;
    },
    SET_USERROLECOLUMNS: (state, data) => {
      state.roleUserColumns = data;
      localStorage.setItem("roleUserColumns", JSON.stringify(data));
    }
  },

  actions: {
    // 登录
    SysLogin({ commit, dispatch }, data) {
      return new Promise((resolve, reject) => {
        setToken(data.token);
        dispatch("tokenGetInfo", data.token).then(res => {
          let userInfo = res.user_info;
          setUserInfo({
            userId: userInfo.user_id,
            role_info: userInfo.role_info[0],
            avatar: require("@/assets/images/profile.jpg"),
            permissions: ["*:*:*"],
            info: userInfo
          });
          commit("SET_TOKEN", data.token);
          commit("SET_NAME", userInfo.user_name);
          commit("SET_PERMISSIONS", ["*:*:*"]);
          commit("SET_AVATAR", require("@/assets/images/profile.jpg"));
          commit("SET_USERINFO", {
            userId: userInfo.user_id,
            role_info: userInfo.role_info[0],
            avatar: require("@/assets/images/profile.jpg"),
            permissions: ["*:*:*"],
            info: userInfo
          });
        });
        resolve();
      });
    },

    //token获取用户信息
    tokenGetInfo({ commit, state }, token) {
      return new Promise((resolve, reject) => {
        tokenuserinfo({ token }).then(res => {
          resolve(res.data);
        });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", "");
        commit("SET_ROLES", []);
        commit("SET_PERMISSIONS", []);
        removeToken();
        resolve();
      });
    }
  }
};

export default user;
